﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
using System.Web;
using System.Data;
using com.dz.ht.common;

namespace com.dz.ht.components
{
    public class ICON_ReviewManager
    {
        /// <summary>
        /// 触发发送消息的事件
        /// </summary>
        public event SendMsgEventHandler SendMsg;

        private const string c_search_url = "http://search.17k.com/query.do?queryString={0}";

        private const string c_comment_url = "http://comment.17k.com/comment/bookCommentList.action?bookId={0}";

        private string m_reg_review="<ol\\s*?style=[\'\"]?overflow:hidden[\'\"]?>\\s*?<li>(.*?)</li>\\s*?</ol>";

        DataManger m_data_mgr = new DataManger();

        private Encoding m_encoding = Encoding.UTF8;

        private long m_book_id;
        private string m_book_name;

        /// <summary>
        /// 书籍ID
        /// </summary>
        public long BookId
        {
            get { return m_book_id; }
            set { m_book_id = value; }
        }

        /// <summary>
        /// 书名
        /// </summary>
        public string BookName
        {
            get { return m_book_name; }
            set { m_book_name = value; }
        }


        /// <summary>
        /// 发送消息到客户端
        /// </summary>
        /// <param name="i_msg"></param>
        private void SendMsg2Client(string i_msg)
        {
            SendMsgEventArgs e = new SendMsgEventArgs();
            e.Msg = i_msg;

            if (SendMsg != null)
            {
                SendMsg(this, e);
            }
        }

        /// <summary>
        /// 单独一本图书
        /// </summary>
        public void StartSingleBook()
        {
            StartBook(BookName, BookId);
        }

        /// <summary>
        /// 所有图书
        /// </summary>
        public void StartAllBook()
        {
            DataSet ds = m_data_mgr.GetBookByReview(2167);

            if (ds != null && ds.Tables[0].Rows.Count > 0)
            {
                long t_book_id = 0;
                for (int index = 0; index < ds.Tables[0].Rows.Count; index++)
                {
                    if (!long.TryParse(ds.Tables[0].Rows[index]["bookid"].ToString(), out t_book_id))
                        t_book_id = 0;

                    StartBook(ds.Tables[0].Rows[index]["bookName"].ToString(), t_book_id);
                }
            }
        }

        /// <summary>
        /// 搜索一本书评论及封面
        /// </summary>
        /// <param name="i_book_url"></param>
        public void StartBook(string i_book_name,long i_book_id)
        {
            string t_html = string.Empty;
            //构造搜索页面
            string t_url = string.Format(c_search_url, HttpUtility.UrlEncode(i_book_name, m_encoding));
            try
            {
                t_html = NetSiteCatchManager.ReadUrl(t_url, m_encoding);

                if (!string.IsNullOrEmpty(t_html))
                {
                    Match t_mc=Regex.Match(t_html,string.Format("<a[^<>]*?hrefs*=s*[\'\"]*([^\"\']*http:\\/\\/www\\.17k\\.com\\/book\\/(\\d+)\\.html)[\'\"]*[^<>]*?>\\s*?<font.*?>{0}</font></a>",i_book_name),RegexOptions.IgnoreCase|RegexOptions.Compiled);

                    if (t_mc != null && t_mc.Groups.Count == 3)
                    {
                        StartBookInfo(t_mc.Groups[1].Value.ToString(), t_mc.Groups[2].Value.ToString(),i_book_name,i_book_id);
                    }
                    else
                    {
                        SendMsg2Client(string.Format("17k不存在图书：{0}", i_book_name));
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取评论失败" + ex.ToString());
            }
        }

        /// <summary>
        /// 搜集图书详情
        /// </summary>
        /// <param name="i_book_url"></param>
        private void StartBookInfo(string i_book_url,string i_book_id,string i_my_book_name,long i_my_book_id)
        {
            string t_html = string.Empty;

            try
            {
                t_html = NetSiteCatchManager.ReadUrl(i_book_url, m_encoding);

                if (!string.IsNullOrEmpty(t_html))
                {
                    Match t_mc=Regex.Match(t_html,"<img[^<>]*srcs*=s*[\'\"]*([^\"\']*http:\\/\\/img\\.17k\\.com\\/images\\/bookcover\\/\\d+\\/\\d+\\/\\d+\\.jpg)[\'\"]*[^<>]*?>",RegexOptions.IgnoreCase|RegexOptions.Compiled);

                    if (t_mc != null && t_mc.Groups.Count == 2)
                    {
                        int t_ret= NetSiteCatchManager.DownLoadImage(t_mc.Groups[1].Value.ToString(), i_my_book_id);
                        if (t_ret == Consts.Success)
                        {
                            SendMsg2Client(string.Format("成功下载：{0}封面", i_my_book_name));
                        }
                    }
                    else
                    {
                        SendMsg2Client(string.Format("17k不存在：{0}封面", i_my_book_name));
                    }
                }

                //收集评论
                string t_review_url = string.Format(c_comment_url, i_book_id);

                t_html = NetSiteCatchManager.ReadUrl(t_review_url, m_encoding);

                if (!string.IsNullOrEmpty(t_html))
                {
                    MatchCollection t_ma = Regex.Matches(t_html, m_reg_review, RegexOptions.IgnoreCase | RegexOptions.Compiled);

                    if (t_ma != null && t_ma.Count > 0)
                    {
                        string t_review_content = string.Empty;
                        foreach (Match t_mc in t_ma)
                        {
                            t_review_content = t_mc.Groups[1].Value.ToString();
                            t_review_content = FilterReviewContent(t_review_content);
                            if (t_review_content.Length > 10)
                            {
                                m_data_mgr.InsertBookReview(i_my_book_id, t_review_content);
                                SendMsg2Client(string.Format("获得书籍：{0} 评论：{1}" ,i_my_book_name, t_review_content));
                            }
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                LogHelper.Error("获取书籍详情失败" + ex.ToString());
            }
        }

        /// <summary>
        /// 过滤评论内容
        /// </summary>
        /// <param name="i_content"></param>
        /// <returns></returns>
        private string FilterReviewContent(string i_content)
        {
            if (string.IsNullOrEmpty(i_content))
                return string.Empty;

            i_content = i_content.Replace("17k", "聚文学");
            i_content = Regex.Replace(i_content, "<img.*?>", "",RegexOptions.IgnoreCase|RegexOptions.Compiled);
            i_content = Regex.Replace(i_content, "htt.*?m", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);
            i_content = Regex.Replace(i_content, "www.*?m", "", RegexOptions.IgnoreCase | RegexOptions.Compiled);

            if (i_content.IndexOf("鲜花") > -1)
                return string.Empty;

            return i_content;

        }
    }
}
